# -*- coding: utf-8 -*-
# !/usr/bin/python3
# @Time    : 2019/12/3 20:40
# @Author  : wenjxu
import pymysql, traceback, re, logging, sys, json, os, time
from core.conf.config import settings
from httprunner.api import HttpRunner
from cacheout import LFUCache
from urllib.parse import urlparse
from requests.cookies import RequestsCookieJar
from jsonpath_rw import jsonpath, parse


class ClearReports(object):

    def __init__(self):
        self.base_dir = settings.BASE_DIR

    def process_request(self):
        reports_path = os.path.join(self.base_dir, "reports")
        if os.listdir(reports_path):
            for item in os.listdir(reports_path):
                try:
                    logging.info("start to del file")
                    html_path = os.path.join(reports_path, item)
                    os.remove(html_path)
                except:
                    traceback.print_exc()
        logging.info("reports is clean")


class MysqlConn(object):

    def __init__(self, config):
        self.config = config

        try:
            self.config['cursorclass'] = pymysql.cursors.DictCursor
            self.conn = pymysql.connect(**self.config)  # 连接数据库
            self.cursor = self.conn.cursor()  # 获取数据库的游标
        except:
            traceback.print_exc()

    def sql_query(self, sql):
        sql = sql.upper()
        try:
            self.cursor.execute(sql)
            fetchmany = self.cursor.fetchmany()
            if not fetchmany:
                logging.warning("no value result,please check the SQL ".format(sql))
                sys.exit(1)
            elif len(fetchmany) > 1 or len(fetchmany[0]) > 1:
                logging.warning("please check the SQL,The query statement can only return one value:{}".format(sql))
                sys.exit(1)
            elif len(fetchmany) == 1 and len(fetchmany[0]) == 1:
                re_field = re.findall("SELECT(.*)FROM", sql)[0].strip()
                res = fetchmany[0].get(re_field)
            else:
                logging.warning("please check the SQL:".format(sql))
                sys.exit(1)
        except:
            traceback.print_exc()
            sys.exit(1)

        return res

    def sql_execute(self, sql):
        if sql.lower().startswith('delete'):
            logging.error("!!!Cannot execute delete SQL")
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except:
            traceback.print_exc()
            self.conn.rollback()


class RunTestCase(object):

    def __init__(self):
        self.cache = LFUCache(maxsize=256, ttl=0, timer=time.time, default=None)

    def httprun(self, file):
        runner = HttpRunner(failfast=False)
        runner.run(file)

    def summary(self, file):
        runner = HttpRunner(failfast=False)
        runner.run(file)

        return runner._summary

    def get_cookies(self, filename):

        if not self.cache.get(filename):
            summary = self.summary(filename)
            domain = urlparse(summary["details"][0]["records"][0]["meta_datas"]["data"][0]["request"]["url"]).netloc
            cookies = summary["details"][0]["records"][0]["meta_datas"]["data"][0]["response"].get("cookies", {})

            if cookies:
                cookie_jar = RequestsCookieJar()
                for k, v in cookies.items():
                    cookie_jar.set(k, v, domain=domain)
                self.cache.set(filename, cookie_jar)
            else:
                logging.warning("the file no cookies")
                return "the file no cookies"

        return self.cache.get(filename)

    def get_response(self, filename, pattern):

        if not self.cache.get(filename):
            summary = self.summary(filename)
            print(json.dumps(summary))
            res = json.loads(summary["details"][0]["records"][0]["meta_datas"]["data"][0]["response"]["body"])

            if res:
                jsonpath_expr = parse(pattern)
                var = [match.value for match in jsonpath_expr.find(res)]
                if len(var) == 1:
                    self.cache.set(filename, var[0])
                else:
                    self.cache.set(filename, var)
            else:
                logging.warning("the file no response")
                return "the file no response"

        return self.cache.get(filename)


run_testcase = RunTestCase()
# baletu_mysql_conn = MysqlConn(settings.DATABASES["baletu"])

